<script setup>
import { ref } from 'vue'
import api from '@/api'
import { parsePage, parseQuery } from '@/utils'
import { useRoute, useRouter } from 'vue-router'
import { Modal } from '@arco-design/web-vue'

const $route = useRoute()
const $router = useRouter()

const listFormData = ref({
  page: parsePage($route.query.page, 1),
  keyword: $route.query.keyword || '',
})
const listData = ref([])
const listTotal = ref(0)
const listLoading = ref(false)
const getListData = async (page = 1) => {
  listLoading.value = true
  try {
    listFormData.value.page = page
    const query = parseQuery(listFormData.value)
    $router.replace({ query })
    const res = await api.get('departments', {
      params: query,
    })
    listData.value = res.data
    listTotal.value = res.total
  } catch (error) {
    console.error(error)
  }
  listLoading.value = false
}

const resetListData = () => {
  listFormData.value.keyword = ''
  getListData()
}

getListData()

const formRef = ref()
const formItem = ref()
const formLoading = ref(false)
const formVisible = ref(false)
const formData = ref({
  name: '',
})
const formRules = {
  name: [
    {
      required: true,
      message: '请填写部门名称',
    },
  ],
}

const create = () => {
  formRef.value?.resetFields()
  formVisible.value = true
}

const update = (item) => {
  formRef.value?.resetFields()
  formItem.value = item
  formData.value.name = item.name
  formVisible.value = true
}

const formSubmit = async () => {
  if (await formRef.value.validate()) {
    return false
  }

  formLoading.value = true

  try {
    if (formItem.value) {
      await api.put('departments/' + formItem.value.id, formData.value)
    } else {
      await api.post('departments', formData.value)
    }
    formRef.value?.resetFields()
    formVisible.value = false
    getListData()
  } catch (error) {
    console.error(error)
  }

  formLoading.value = false

  return false
}

const del = (department) => {
  Modal.confirm({
    title: '删除部门',
    content: '您确定要删除吗？',
    bodyStyle: 'text-align:center',
    onBeforeOk: async () => {
      await api.delete('departments/' + department.id)

      getListData()
    },
  })
}
</script>

<template>
  <div class="page">
    <div class="header">
      <a-space>
        <a-button type="primary" @click="create">添加部门</a-button>
      </a-space>
      <a-form
        :model="listFormData"
        class="page-form"
        layout="inline"
        @submit="getListData(1)"
      >
        <a-space>
          <a-input
            v-model="listFormData.keyword"
            placeholder="部门名称"
            allow-clear
          />
          <a-button type="primary" html-type="submit">
            <template #icon><icon-search /></template>
            查询
          </a-button>
          <a-button @click="resetListData">
            <template #icon><icon-refresh /></template>重置
          </a-button>
        </a-space>
      </a-form>
    </div>

    <a-table
      :loading="listLoading"
      @page-change="getListData"
      class="table"
      :data="listData"
      :pagination="{
        simple: true,
        showTotal: true,
        size: 'small',
        total: listTotal,
        pageSize: 20,
        current: listFormData.page,
      }"
    >
      <template #columns>
        <a-table-column title="序号" :width="60">
          <template #cell="{ rowIndex }"> {{ rowIndex + 1 }} </template>
        </a-table-column>
        <a-table-column title="名称" data-index="name"></a-table-column>
        <a-table-column align="right" :width="88">
          <template #cell="{ record }">
            <a-space>
              <a-button type="primary" size="mini" @click="update(record)"
                >编辑</a-button
              >
              <a-button
                type="primary"
                status="danger"
                size="mini"
                @click="del(record)"
              >
                删除
              </a-button>
            </a-space>
          </template>
        </a-table-column>
      </template>
    </a-table>

    <a-modal
      v-model:visible="formVisible"
      :title="(formItem ? '编辑' : '添加') + '部门'"
      width="800px"
      :ok-loading="formLoading"
      :on-before-ok="formSubmit"
    >
      <a-form ref="formRef" :model="formData" :rules="formRules">
        <a-form-item field="name" label="部门名称">
          <a-input v-model="formData.name" allow-clear />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
